<template>
	<view class="home" :style="bgStyle">
		<custom-navbar title="投融资" :show-back="true" @back="handleBack" />

		<view class="content p30 pb150 mt30" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="co-operatingAgency  bg-image mb40">
				<!-- 滑动容器 -->
				<swiper class="swiper" :current="current" @change="swiperChange" :indicator-dots="false"
					v-if="pages.length > 0">
					<swiper-item v-for="(page, index) in pages" :key="index">
						<view class="page">
							<view class="item" v-for="(item, i) in page" :key="i" @click="handleItemClick(item)">
								<image class="item-img" :src="item.image" mode="aspectFit" @error="handleImageError" />
							</view>
						</view>
					</swiper-item>
				</swiper>
				<!-- 自定义页码指示器 -->
				<view class="indicator">
					<view v-for="(dot, index) in pages.length" :key="index" class="dot"
						:class="{ 'active': current === index }"></view>
				</view>
			</view>
			<view class="search mb40">
				<view class="box fcc mb30 p016016">
					<up-search shape="square" placeholder="请输入产品名称或银行名称" v-model="keyword"
						:showAction="false"></up-search>
					<up-button type="primary" @click="getProductName()"
						style="width: 140rpx;height: 60rpx;background: #398DFB;border-radius: 10rpx 10rpx 10rpx 10rpx;"
						text="确定"></up-button>
				</view>
				<view class="flex ">
					<view v-for='(item,index) in data16' class="typelist fcolcc" style="margin-right: 67rpx;">
						<view class="f30bc3" :class="finance_category == item.value ? 'c398DFB' :''"
							@click="Switchingfinance_category(item.value)">
							{{item.label}}
						</view>
						<view :class="finance_category == item.value ? 'underline' :''"></view>
					</view>
				</view>
			</view>
			<view class="list">
				<view class="item p30 mb20" v-for="(item,index) in List" key="index" @click="handleProductClick(item)">
					<view class="f306c3 mb18">{{item.finance_title}}</view>
					<view class="fc mb35">
						<view v-for="(items,index) in item.product_tags_text" key="index" class="p0020 fcc tips mr10">
							{{items}}
						</view>
					</view>
					<view class="f22c9">{{item.institution_name}}</view>
					<up-line margin='12rpx 0 30rpx 0'></up-line>
					<view class="fcsb">
						<view class="f22c9">起止时间:{{item.start_time}}至{{item.end_time}}</view>
						<view @click.stop="toggleCollection(item)">
							<image v-if="item.is_collection == 0" class="wh36" src="/static/images/talents/未收藏.svg">
							</image>
							<image v-else class="wh36" src="/static/images/talents/已收藏.svg"></image>
						</view>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		useUserStore
	} from '@/stores/user'
	import {
		useI18n
	} from 'vue-i18n'

	import CustomNavbar from '@/components/custom-navbar.vue'
	// 获取全局cdn方法
	const {
		proxy
	} = getCurrentInstance()
	const cdn = (path) => proxy.$cdn + path
	const {
		t
	} = useI18n()
	import {
		getClassification,
		saveCollection
	} from '@/api/login'
	import {
		lists,
		institutionLists
	} from '@/api/finance'

	const userStore = useUserStore()
	const searchKey = ref('')

	// 登录状态：'loading'|'success'|'error'
	const loginStatus = ref('loading')

	// 获取系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)
	const bgStyle = ref({})

	const data16 = ref([])
	const loading = ref(false)
	// 单独请求 getClassification(16) 接口
	const fetchData = async () => {
		try {
			loading.value = true
			const res = await getClassification(5)
			data16.value = res.data
			finance_category.value = data16.value[0]?.value || '' // 添加可选链操作符防止undefined
			getinstitutionLists()
			getlists()
		} catch (error) {
			console.error('请求分类数据失败:', error)
			uni.showToast({
				title: '加载分类失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 初始化
	onMounted(() => {
		bgStyle.value = {
			backgroundImage: `url(https://gx.jifgou.com/image/homebg.png)`,
			backgroundSize: '100% auto',
			backgroundRepeat: 'no-repeat',
			minHeight: '100vh'
		}
		fetchData()
	})
	const finance_category = ref('')
	const page = ref(1)
	const limit = ref(10)
	const keyword = ref('')
	const financingList = ref([])
	const total = ref(0)
	const getinstitutionLists = async () => {
		const parmas = {
			lang_code: 'zh',
			limit: limit.value,
			page: page.value,

		}
		try {
			const Res = await institutionLists(parmas)
			if (Res.code === 200) { // 注意这里是 ===，不是 =
				financingList.value = Res.data.data

			}
		} catch (error) {
			console.error('获取直播列表失败:', error)
			uni.showToast({
				title: '加载直播列表失败',
				icon: 'none'
			})
		}
	}
	const List = ref([])
	const getlists = async () => {
		const parmas = {
			lang_code: 'zh',
			limit: limit.value,
			page: page.value,
			institution_id: '',
			finance_category: finance_category.value,
			keyword: keyword.value

		}
		try {
			const Res = await lists(parmas)
			if (Res.code === 200) { // 注意这里是 ===，不是 =
				List.value = Res.data.data

			}
		} catch (error) {
			console.error('获取列表失败:', error)
			uni.showToast({
				title: '加载列表失败',
				icon: 'none'
			})
		}
	}
	const getProductName = () => {
		getlists()
	}
	const Switchingfinance_category = (val) => {
		finance_category.value = val
		getlists()
	}
	const handleBack = () => {
		uni.switchTab({
			url: '/pages/index/index'
		});
	};
	// 模拟数据 - 假设有12个项目
	const items = computed(() => {
		return financingList.value.map(item => ({
			id: item.institution_id,
			image: item.institution_logo || '/static/logo.png',
			// 其他需要展示的字段
		}));
	});

	// 当前页索引
	const current = ref(0);

	// 将数据分页，每页6个
	const pages = computed(() => {
		const result = [];
		for (let i = 0; i < items.value.length; i += 6) {
			result.push(items.value.slice(i, i + 6));
		}
		return result;
	});

	// 滑动切换回调
	const swiperChange = (e) => {
		current.value = e.detail.current;
	};


	// 点击合作机构项目回调
	const handleItemClick = (item) => {
		console.log('点击了机构:', item);
		uni.navigateTo({
			url: `/pages/financing/organization?institution_id=${item.id}`
		})

	};
	// 点击产品
	const handleProductClick = (item) => {
		console.log('点击了金融产品:', item);
		uni.navigateTo({
			url: `/pages/financing/product?finance_id=${item.finance_id}`
		})

	};
	const toggleCollection = async (item) => {
		try {
			const res = await saveCollection({
				type: 5, // 5代表投融资类型
				collection_id: item.finance_id // 使用金融产品的ID
			})

			if (res.code === 200) {
				// 更新当前项的收藏状态
				item.is_collection = item.is_collection == 0 ? 1 : 0
				uni.showToast({
					title: item.is_collection ? '收藏成功' : '已取消收藏',
					icon: 'none'
				})
				getlists()
			} else {
				throw new Error(res.message || '操作失败')
			}
		} catch (error) {
			console.error('收藏操作失败:', error)
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		position: relative;
		background-size: 100% auto;
		background-repeat: no-repeat;

		.content {
			padding: 30rpx;
			padding-bottom: 150rpx;

			.co-operatingAgency {
				width: 100%;
				min-height: 468rpx;
				padding: 70rpx 46rpx 30rpx 40rpx;
				box-sizing: border-box;
				border-radius: 16rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.swiper {
					height: 320rpx;
					/* 明确高度 */

					.page {
						display: flex;
						flex-wrap: wrap;
						justify-content: space-between; // 关键点1：使用space-between自动分配间距
						row-gap: 70rpx;
						width: 100%;
						height: 100%;

						// 关键点2：为每个item设置固定宽度和margin
						.item {
							width: 148rpx !important;
							height: 148rpx !important;
							margin-right: calc((100% - 148rpx * 3) / 2); // 计算剩余空间平均分配

							// 关键点3：每第三个item清除右边距
							&:nth-child(3n) {
								margin-right: 0;
							}

							// 关键点4：当只有1个或2个item时保持左对齐
							&:only-child,
							&:nth-child(2):last-child {
								margin-right: auto;
							}

							background: #fff;
							border-radius: 12rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							.item-img {
								width: 80%;
								height: 80%;
								object-fit: contain;
							}
						}
					}
				}

				.indicator {
					display: flex;
					justify-content: center;
					align-items: center;
					height: 20rpx;
					margin-top: auto;

					.dot {
						width: 5rpx;
						/* 小圆点直径 */
						height: 5rpx;
						/* 小圆点直径 */
						background: #D9D9D9;
						/* 未激活状态 - 灰色小圆 */
						border-radius: 50%;
						/* 圆形 */
						margin: 0 4rpx;
						/* 间距 */
						transition: all 0.3s ease;

						&.active {
							width: 50rpx;
							/* 激活状态 - 蓝色短线条 */
							height: 5rpx;
							background: #398DFB;
							border-radius: 3rpx;
							/* 轻微圆角 */
						}
					}
				}
			}

			.bg-image {
				background-image: url('https://gx.jifgou.com/image/投融资bg.png');
				background-size: cover;
				background-repeat: no-repeat;
				background-position: center;
			}

			.box {
				width: 100%;
				height: 90rpx;
				background: #F3F3F3;
				border-radius: 10rpx 10rpx 10rpx 10rpx;
			}

			.typelist {
				position: relative;

				.underline {
					width: 40rpx;
					height: 4rpx;
					background: #398DFB;
					border-radius: 500rpx 500rpx 500rpx 500rpx;
					position: absolute;
					bottom: -23rpx;
					// left: 0;
				}
			}

			.list {
				.item {
					width: 100%;
					height: 300rpx;
					background: #FFFFFF;
					border-radius: 20rpx 20rpx 20rpx 20rpx;
					border: 1rpx solid;
					border-image: linear-gradient(61deg, rgba(57, 141, 251, 0), rgba(255, 255, 255, 1)) 1 1;

					.tips {
						height: 44rpx;
						background: rgba(57, 141, 251, 0.1);
						border-radius: 8rpx 8rpx 8rpx 8rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 20rpx;
						color: #398DFB;
						line-height: 44rpx;
						text-align: center;
						font-style: normal;
						text-transform: none;
					}
				}
			}
		}
	}
</style>